import UIKit

@objc
protocol AlertViewDelegate: NSObjectProtocol {
   optional func alertViewTapCancel(alertView: AlertView)
   optional func alertViewTapOK(alertView: AlertView, textField: UITextField)
}

class AlertView: UIView {
    
    weak var delegate: AlertViewDelegate?
    
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var alertView: UIView!
    @IBOutlet weak var textField: UITextField!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        addGestureRecognizer(tapGestureRecognizer)
        alertView.addGestureRecognizer(tapAlberBackground)
        
    }
    
    private lazy var tapGestureRecognizer: UITapGestureRecognizer = {
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AlertView.didTapBackground))
        return tapGestureRecognizer
    }()
    
    func didTapBackground() {
        didTapCancel(nil)
    }
    
    private lazy var tapAlberBackground: UITapGestureRecognizer = {
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AlertView.didTapAlertView))
        return tapGestureRecognizer
    }()
    
    func didTapAlertView() {
    }
    
    class func build(title: String, placeholder: String) -> AlertView {
        
        let alertView = NSBundle.mainBundle().loadNibNamed(AlertView.className, owner: nil, options: nil).last as! AlertView
        alertView.frame = UIScreen.mainScreen().bounds
        alertView.titleLabel.text = title
        alertView.textField.placeholder = placeholder
        
        return alertView
    }
    
    func showInView() {
        if let view = UIApplication.sharedApplication().keyWindow {
            view.addSubview(self)
        }
    }
    
    @IBAction func didTapOK(sender: AnyObject) {
        delegate?.alertViewTapOK?(self, textField: textField)
    }
    
    @IBAction func didTapCancel(sender: AnyObject?) {
        delegate?.alertViewTapCancel?(self)
        removeFromSuperview()
    }
    
    func hide() {
        didTapCancel(nil)
    }
    
    deinit {
        print("AlertView: deinit")
    }
}
